package com.wei.web.interceptor;

import com.wei.annotation.AuthorityVerify;
import com.wei.service.wrapper.HttpContextWrapper;
import com.wei.utils.ApplicationConstants;
import com.wei.utils.ExceptionUtils;
import com.wei.utils.Stringutils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PatientAuthorityHandler implements HandlerInterceptor {
    @Autowired
    private HttpContextWrapper wrapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            return true;
        }
        HandlerMethod handlerMethod = ((HandlerMethod) handler);
        AuthorityVerify authorityVerify = handlerMethod.getMethod().getDeclaringClass().getAnnotation(AuthorityVerify.class);
        if (authorityVerify == null) {
            authorityVerify = handlerMethod.getMethodAnnotation(AuthorityVerify.class);
        }
        if (authorityVerify == null) {
            return true;
        }
        if (Stringutils.isEmptyOrWhiteSpace(wrapper.getToken())) {
            throw ExceptionUtils.mpeValidator("%s", "请先登录!");
        }
        if(wrapper.CurrentPatient()==null){
            throw ExceptionUtils.mpeValidator("%s", "请先绑定患者!");
        }
        return true;
    }
}
